__author__ = 'Jay'
import pandas as pd
import os
import pytz
from datetime import datetime
import pymongo
import json
from time import time
import MySQLdb


def _get_stocks_from_db():
    # connect to mysql
    conn = MySQLdb.connect(host='rdsqtehrv8tqh7v60yvujpublic.mysql.rds.aliyuncs.com',
                           user='tradingfloor',
                           passwd='tradingfloor123',
                           db='tradingreason',
                           charset='utf8')
    # conn = MySQLdb.connect(host='localhost',
    #                   user='root',
    #                   passwd='root',
    #                   db='tradingreasontt',
    #                   charset='utf8')
    cur = conn.cursor()
    res = []
    cur.execute("select symbol from stock_info")
    for (symbol,) in cur:
        res.append(symbol)
    return res


t0 = time()

tz = pytz.timezone(pytz.country_timezones('cn')[0])
start = datetime(2015, 12, 21, 0, 0, tzinfo=tz)
end = datetime(2015, 12, 29, 0, 0, tzinfo=tz)

log = open('resample_log.txt', 'a')
td = datetime.today()
log.write('#####################################################\n')
log.write('task begins at: ' + td.strftime('%Y-%m-%d %H:%M:%S') + '\n')
log.write('data range:\n')
log.write('start date :' + start.strftime('%Y-%m-%d %H:%M:%S') + '\n')
log.write('end date :' + end.strftime('%Y-%m-%d %H:%M:%S') + '\n')

client = pymongo.MongoClient('121.40.212.219', 27017)  # '121.40.212.219', 27017
db = client.Daily_data

seclist = _get_stocks_from_db()

for sec in seclist:
    cur = db.qfq_data.find({'symbol': sec, 'dateTime': {'$gte': start, '$lte': end}}, {'_id': 0}) \
        .sort("dateTime", pymongo.ASCENDING)
    datas = list(cur)
    if len(datas) > 0:
        prePrice = datas[0]['close']
        for i in range(1, len(datas) - 1):
            price = datas[i]['close']
            rate = (price - prePrice) / prePrice
            prePrice = price
            if rate > 0.11:
                print datas[0]['symbol']
                break
